import time
from datetime import datetime

import pandas
import pandas as pd
import geopandas as geo
import matplotlib.pyplot as plt
from math import cos, sin, atan2, sqrt, pi, radians, degrees



# pandas显示所有行
from shapely import wkt

pd.set_option('display.max_rows', None)
# 设置pandas显示的列数
pd.set_option('display.max_columns', 20)
# 让dataframe打印不换行
pd.set_option('display.width', 5000)


# 设置画板
fig = plt.figure(1, (16, 8), dpi=100)
ax = plt.subplot(111)
plt.sca(ax)
def ptype(file):
    print(type(file))

def pd_show(file):
    print(file.shape)
    print(file.head(3))

def center_geolocation(geolocations):
    x = 0
    y = 0
    z = 0
    lenth = len(geolocations)
    for lon, lat in geolocations:
        lon = radians(float(lon))
        lat = radians(float(lat))

        x += cos(lat) * cos(lon)
        y += cos(lat) * sin(lon)
        z += sin(lat)

    x = float(x / lenth)
    y = float(y / lenth)
    z = float(z / lenth)

    return (degrees(atan2(y, x)), degrees(atan2(z, sqrt(x * x + y * y))))


# draw newyork map to artboard
map = geo.read_file('../data/map/NewYork.shp')
map.plot(ax=ax, edgecolor=(0, 0, 0, 1), facecolor=(0, 0, 0, 0), linewidths=0.5)

# point = geo.read_file('D:/PythonWork/pythonProject4/zipCar2/point_grid.shp')
# print(point.shape)
# print(point.head())
# point.plot(ax=ax, edgecolor=(0, 0, 0, 1), facecolor=(1, 0, 0, 1), linewidths=0, markersize=10)
#
# station = pd.read_csv('E:/DataSet/zipcar_now/nextData/station.csv')
# print(station.shape)
# print(station)
# plt.scatter(x=station['lon'],y=station['lat'],marker='o',s=15, c='blue')
#
#
#
# temp = station.loc[station['carSize']>=5,:]
# temp['geometry']=temp['geometry'].apply(wkt.loads)
# temp = geo.GeoDataFrame(temp,geometry=temp['geometry'])
# print(temp.shape)
# print(temp.head())
# temp = geo.GeoDataFrame(temp,geometry=temp['geometry'])
# temp.plot(ax=ax, edgecolor=(0, 0, 0, 1), facecolor=(1, 0, 0, 0), linewidths=1)
# print(temp['carShare'].tolist())
#
# grid = geo.read_file('E:/DataSet/zipcar_now/nextData/grid.shp')
# print(grid.shape)
# print(grid.head())
# grid.plot(ax=ax, edgecolor=(0, 0, 0, 1), facecolor=(0, 0, 0, 0), linewidths=0.5)
# # zip = geo.read_file()


# print()


grid = geo.read_file('E:/共享出行/Project/data/Grid/grid_1km.shp')
pd_show(grid)
# grid.plot(ax=ax, edgecolor=(0, 0, 0, 1), facecolor=(0, 0, 0, 0), linewidths=0.5)

xiangjiao = geo.read_file('../data/myz/xiangjiao.shp')
plt.scatter(xiangjiao['lat'],xiangjiao['lon'],marker='o',c='blue',s=10)
ids = xiangjiao['id'].tolist()
pd_show(xiangjiao)
xiangjiao_grp= xiangjiao.groupby(['id'])
ids = []
carSize = []
lon = []
lat = []

for name,group in xiangjiao_grp:
    # ids.append(name)
    # print(group)
    points = []
    temp_id = 0
    temp_space = 0
    # print(group)
    for index, row in group.iterrows():
        coordinate = []
        coordinate.append(row.geometry[0].x)
        coordinate.append(row.geometry[0].y)
        # coordinate.append(row.geoms.x)
        # coordinate.append(row.geoms.y)
        points.append(coordinate)
        temp_id = row.id
        temp_space += row.carSize
    center_tuple = center_geolocation(points)
    lon.append(center_tuple[0])   # return (-73.78509245732995, 40.712174305836356) tuple
    lat.append(center_tuple[1])   # return (-73.78509245732995, 40.712174305836356) tuple
    ids.append(temp_id)
    carSize.append(temp_space)
site = pandas.DataFrame({'id':ids,'carSize':carSize,'lon':lon,'lat':lat})
pd_show(site)
# plt.scatter(site['lon'],site['lat'],marker='o',c='red',s=5)

temp = pd.DataFrame(grid)
res_grid = pd.merge(site,temp,on='id')
pd_show(res_grid)
ptype(res_grid)
g_res_grid = geo.GeoDataFrame(res_grid,geometry='geometry')
ptype(g_res_grid)
sss = g_res_grid['carSize'].tolist()
print(sum(sss))

temp_grid = g_res_grid[g_res_grid['carSize']>3]
temp_grid.plot(ax=ax, edgecolor=(0, 0, 0, 1), facecolor=(1, 0, 0, 0), linewidths=0.5)
plt.scatter(temp_grid['lon'],temp_grid['lat'],marker='o',c='red',s=5)
pd_show(temp_grid)
print(temp_grid)
car_size = temp_grid['carSize'].tolist()
print(sum(car_size))

temp_grid['carSpace'] = temp_grid['carSize']
temp_grid['carSize'] = temp_grid['carSize'].map(lambda x:x*0.7)
temp_grid['carSize'] = temp_grid['carSize'].astype(int)
# pd_show(temp_grid)
# 这里的temp_grid的id还是原来1km网格的id
temp_grid = temp_grid.drop(['left','top','right','bottom'],axis=1).copy()
pd_show(temp_grid)
#我们在这里将temp_grid的id重置
temp_grid.reset_index(drop=True,inplace=True)
temp_grid['id'] = temp_grid.index
pd_show(temp_grid)
print(temp_grid)
#这里得到的temp_grid已经是包含站点经纬度，车站容量，车站车辆数的站点，下一步是对数据进行清洗，首先清除od不在网格的订单，然后清除时间小于5分钟，od在同一个网格的订单。
# 将站点信息保存到本地
temp_grid.to_file('./myz/res_station2.shp',index=False)
plt.show()
